package com.swz.dcrm.ui.monthly;


import android.graphics.Typeface;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bigkoo.pickerview.TimePickerView;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.swz.dcrm.adpter.GlobalAdapter;
import com.swz.dcrm.model.BaseResponse;
import com.swz.dcrm.model.DeliveryAndCancleOrderCount;
import com.swz.dcrm.model.MonthlyGraph;
import com.swz.dcrm.ui.base.BaseFragment;
import com.swz.dcrm.R;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.navigation.fragment.NavHostFragment;

import android.widget.TextView;

import butterknife.BindView;
import butterknife.OnClick;

import com.swz.dcrm.R;
import com.swz.dcrm.ui.viewmodel.AnalyzeViewModel;
import com.swz.dcrm.util.DateUtils;
import com.swz.dcrm.util.Tool;
import com.swz.dcrm.widget.MyMarkerView;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * A simple {@link Fragment} subclass.
 */
public class MonthlyGraphFragment extends BaseFragment {


    @BindView(R.id.line_chart1)
    LineChart lineChart1;
    @BindView(R.id.line_chart2)
    LineChart lineChart2;
    @BindView(R.id.line_chart3)
    LineChart lineChart3;
    @BindView(R.id.tv_build_count)
    TextView tvBuildCount;
    @BindView(R.id.tv_defeated_count)
    TextView tvDefeatedCount;
    @BindView(R.id.tv_come_shop_count)
    TextView tvComeShopCount;
    @BindView(R.id.tv_order_count)
    TextView tvOrderCount;
    @BindView(R.id.tv_delivery_count)
    TextView tvDeliveryCount;
    @BindView(R.id.tv_cancel_order_count)
    TextView tvCancelOrderCount;



    private List<String> xList;
    @Inject
    AnalyzeViewModel analyzeViewModel;

    public static MonthlyGraphFragment newInstance() {

        return new MonthlyGraphFragment();
        // Required empty public constructor
    }

    @Override
    public void onLoadRetry() {
        if (!isNetworkConnected(getContext())) {
            mHolder.showLoadingStatus(GlobalAdapter.NET_ERROR);
            return;
        }
        analyzeViewModel.getMonthlyGraph().observe(this, observer);

    }

    Observer observer = (Observer<BaseResponse<MonthlyGraph>>) monthlyGraphBaseResponse -> {
        if (monthlyGraphBaseResponse.isSuccess()) {
            MonthlyGraph monthlyGraph = monthlyGraphBaseResponse.getData();
            List<Integer> list=new ArrayList<>();
            List<Integer> list1=new ArrayList<>();
            xList=new ArrayList<>();

            for ( MonthlyGraph.BuildDefeatedItem buildDefeatedItem:monthlyGraph.getBuildDefeatedList()){
                list.add(buildDefeatedItem.getCreateFileCount());
                list1.add(buildDefeatedItem.getDefeatedCount());
                xList.add(buildDefeatedItem.getStatisticsTime());
            }
            showLineChart(lineChart1,list,"新建档数",list1,"战败数");
            initChart(lineChart1);
            MyMarkerView myMarkerView=new MyMarkerView(getContext(),xList);
            myMarkerView.setChartView(lineChart1);
            lineChart1.setMarker(myMarkerView);
            tvBuildCount.setText(getSpannableString(getString(R.string.monthly_build_count,monthlyGraph.getBuildFileCount())));
            tvDefeatedCount.setText(getSpannableString(getString(R.string.monthly_defeated_count,monthlyGraph.getDefeatedCount())));
            tvCancelOrderCount.setText(getSpannableString(getString(R.string.monthly_cancel_count,monthlyGraph.getCancelOrderCount())));
            tvComeShopCount.setText(getSpannableString(getString(R.string.monthly_come_shop_count,monthlyGraph.getComeShopCount())));
            tvDeliveryCount.setText(getSpannableString(getString(R.string.monthly_delivery_count,monthlyGraph.getDeliveryCarCount())));
            tvOrderCount.setText(getSpannableString(getString(R.string.monthly_order_count,monthlyGraph.getOrderCount())));


             list=new ArrayList<>();
             list1=new ArrayList<>();
            xList=new ArrayList<>();

            for ( MonthlyGraph.ComeShopAndOrderItem comeShopAndOrderItem:monthlyGraph.getComeShopAndOrderList()){
                list.add(comeShopAndOrderItem.getComeShopCount());
                list1.add(comeShopAndOrderItem.getOrderCount());
                xList.add(comeShopAndOrderItem.getStatisticsTime());
            }
            showLineChart(lineChart2,list,"到店数",list1,"订车数");
            initChart(lineChart2);
            MyMarkerView myMarkerView1=new MyMarkerView(getContext(),xList);
            myMarkerView1.setChartView(lineChart2);
            lineChart2.setMarker(myMarkerView1);

            list=new ArrayList<>();
            list1=new ArrayList<>();
            xList=new ArrayList<>();

            for ( MonthlyGraph.DeliveryCancelItem deliveryCancelItem:monthlyGraph.getDeliveryCancelList()){
                list.add(deliveryCancelItem.getDeliveryCarCount());
                list1.add(deliveryCancelItem.getCancelOrderCount());
                xList.add(deliveryCancelItem.getStatisticsTime());
            }
            showLineChart(lineChart3,list,"交车数",list1,"退订数");
            initChart(lineChart3);
            MyMarkerView myMarkerView2=new MyMarkerView(getContext(),xList);
            myMarkerView2.setChartView(lineChart3);
            lineChart3.setMarker(myMarkerView2);
        }
    };

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        onLoadRetry();
    }

    @Override
    public int layoutId() {
        return R.layout.fragment_monthly_graph;
    }

    @Override
    public boolean initView() {
        getDigger().inject(this);
        return false;
    }

    private void initLineDataSet(LineDataSet lineDataSet, int color, LineDataSet.Mode mode) {
        lineDataSet.setColor(color);
        lineDataSet.setCircleColor(color);
        lineDataSet.setLineWidth(1f);
        lineDataSet.setCircleRadius(3f);
        //设置曲线值的圆点是实心还是空心
        lineDataSet.setDrawCircleHole(false);
        lineDataSet.setDrawValues(false);
        lineDataSet.setValueFormatter(new IValueFormatter() {
            @Override
            public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                return String.valueOf((int) value);
            }
        });

        //设置折线图填充
        lineDataSet.setDrawFilled(false);
        lineDataSet.setFormSize(15.f);
        if (mode == null) {
            //设置曲线展示为圆滑曲线（如果不设置则默认折线）
            lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        } else {
            lineDataSet.setMode(mode);
        }
    }

    public SpannableString getSpannableString(String str){
        AbsoluteSizeSpan absoluteSizeSpan12;
        AbsoluteSizeSpan absoluteSizeSpan18;
        ForegroundColorSpan foregroundColorSpanlight;
        ForegroundColorSpan foregroundColorSpanDark;
        StyleSpan styleSpan=new StyleSpan(Typeface.BOLD);

        absoluteSizeSpan12=new AbsoluteSizeSpan(Tool.dip2px(getActivity(),12));
        absoluteSizeSpan18=new AbsoluteSizeSpan(Tool.dip2px(getActivity(),18));
        foregroundColorSpanlight=new ForegroundColorSpan(getResources().getColor(R.color.black_2f3234));
        foregroundColorSpanDark=new ForegroundColorSpan(getResources().getColor(R.color.gary_6f777d));

        SpannableString spannableString = new SpannableString(str);

        spannableString.setSpan(foregroundColorSpanlight, 0,str.indexOf('\n'), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(styleSpan,0,str.indexOf('\n'),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(absoluteSizeSpan18,0,str.indexOf('\n'),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(foregroundColorSpanDark, str.indexOf('\n'),str.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(absoluteSizeSpan12,str.indexOf('\n'),str.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannableString;
    }
    /**
     * 展示曲线
     *
     * @param dataList 数据集合
     */
    public void showLineChart(LineChart lineChart, List<Integer> dataList, String title, List<Integer> data1, String title1) {
        List<Entry> entries = new ArrayList<>();
        for (int i = 0; i < dataList.size(); i++) {
            Entry entry = new Entry(i, Float.valueOf(dataList.get(i)));
            entries.add(entry);

        }
        // 每一个LineDataSet代表一条线
        LineDataSet lineDataSet = new LineDataSet(entries, title);
        initLineDataSet(lineDataSet, getResources().getColor(R.color.blue_0f6eff), LineDataSet.Mode.LINEAR);
        LineData lineData = new LineData(lineDataSet, getLine(data1, title1));
        lineChart.setData(lineData);


    }

    /**
     * 添加曲线
     */
    private LineDataSet getLine(List<Integer> dataList, String title) {
        List<Entry> entries = new ArrayList<>();
        for (int i = 0; i < dataList.size(); i++) {
            Entry entry = new Entry(i, dataList.get(i));
            entries.add(entry);
        }
        // 每一个LineDataSet代表一条线
        LineDataSet lineDataSet = new LineDataSet(entries, title);
        lineDataSet.setLabel(title);

        initLineDataSet(lineDataSet, getResources().getColor(R.color.orange_ff8730), LineDataSet.Mode.LINEAR);
        return lineDataSet;


    }
    private void initChart(LineChart lineChart) {

        Description description = new Description();
//        description.setText("需要展示的内容");
        description.setEnabled(false);
        lineChart.setDescription(description);
         XAxis xAxis;                //X轴
         YAxis leftYAxis;            //左侧Y轴
         YAxis rightYaxis;           //右侧Y轴
         Legend legend;
        /***图表设置***/
        //是否展示网格线
        lineChart.setDrawGridBackground(false);
        //是否显示边界
        lineChart.setDrawBorders(false);
        //是否可以拖动
        lineChart.setDragEnabled(false);
        //是否有触摸事件
        lineChart.setTouchEnabled(true);
        //设置XY轴动画效果
        lineChart.animateY(0);
        lineChart.animateX(0);

        /***XY轴的设置***/
        xAxis = lineChart.getXAxis();
        xAxis.setDrawGridLines(false);
        leftYAxis = lineChart.getAxisLeft();
        leftYAxis.setDrawGridLines(true);
        rightYaxis = lineChart.getAxisRight();
        //X轴设置显示位置在底部
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setAxisMinimum(0f);
        xAxis.setGranularity(1f);
        leftYAxis.setValueFormatter((value, axis) -> {
            Float f=value;
            int i=f.intValue();

            if(f>i){
                return "";
            }else {
                return String.valueOf((int)value);
            }
        });
        rightYaxis.setValueFormatter((value, axis) -> {
            Float f=value;
            int i=f.intValue();

            if(f>i){
                return "";
            }else {
                return String.valueOf((int)value);
            }       });
        xAxis.setValueFormatter((value, axis) -> {
            if (xList.size() <= value) {
                return "";
            }
            String date = DateUtils.dateFormat(xList.get((int) value), "MM-dd");
            return date;
        });


        //保证Y轴从0开始，不然会上移一点
        leftYAxis.setAxisMinimum(0f);
        rightYaxis.setAxisMinimum(0f);

        /***折线图例 标签 设置***/
        legend = lineChart.getLegend();
        //设置显示类型，LINE CIRCLE SQUARE EMPTY 等等 多种方式，查看LegendForm 即可
        legend.setForm(Legend.LegendForm.SQUARE);
        legend.setTextSize(12f);

        //显示位置 左上方
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        legend.setYOffset(20);
        legend.setXEntrySpace(10);

        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        //是否绘制在图表里面
        legend.setDrawInside(false);

    }
}
